package cn.kent.high.juc.queue;

import java.util.Random;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * DelayQueue 无界阻塞延迟队列
 * 每个元素都有过期时间，只有过期元素才会出列，队列头元素是快要过期的元素
 *
 * 队列中每个元素都需要实现Delayed接口
 */
public class DelayQueueTest {
    public static void main(String[] args) {
        DelayQueue<DelayEle> queue = new DelayQueue<>();
        // 创建延迟队列
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            DelayEle e = new DelayEle(random.nextInt(500), "task:" + i);
            queue.offer(e);
        }

        // 依次取出任务并打印
        DelayEle ele = null;
        try {
            // 循环，如果想避免虚假唤醒，则不能把全部元素都打印出来
            for (; ; ) {
                // 获取过期任务并打印
                while ((ele = queue.take()) != null) {
                    System.out.println(ele.toString());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    static class DelayEle implements Delayed {
        private final long delayTime; // 延迟时间
        private final long expire; //到期时间
        private String taskName; // 任务名称

        DelayEle(long delay, String taskName) {
            delayTime = delay;
            this.taskName = taskName;
            expire = System.currentTimeMillis() + delay;
        }


        /**
         * 剩余时间=到期时间-当前时间
         */
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        /**
         * 优先级队列里面的优先级规则
         */
        @Override
        public int compareTo(Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }

        @Override
        public String toString() {
            return "DelayEle{" +
                    "delayTime=" + delayTime +
                    ", expire=" + expire +
                    ", taskName='" + taskName + '\'' +
                    '}';
        }
    }
}
